package com.pactera.jep.service.sys.web.controller;

import com.pactera.jep.autoconfigure.web.controller.BaseRestController;
import com.pactera.jep.core.code.YesNo;
import com.pactera.jep.core.exception.ServiceException;
import com.pactera.jep.core.security.token.Token;
import com.pactera.jep.core.security.token.TokenService;
import com.pactera.jep.orm.Filter;
import com.pactera.jep.orm.Operator;
import com.pactera.jep.orm.Order;
import com.pactera.jep.orm.OrderType;
import com.pactera.jep.sys.model.Menu;
import com.pactera.jep.sys.service.MenuService;
import com.pactera.jep.web.code.WebCode;
import com.pactera.jep.web.entity.TreeNode;
import com.pactera.jep.web.util.RequestUtils;
import com.pactera.jep.web.util.TreeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(value = "菜单管理")
@RestController
@RequestMapping("/menu")
public class MenuRestController extends BaseRestController {

    private static Logger log = LoggerFactory.getLogger(MenuRestController.class);

    @Autowired
    MenuService menuService;

    @Autowired
    private TokenService tokenService;

    @ApiOperation(value = "异步加载数据")
    @GetMapping(value = "/treeNode")
    public List<TreeNode> treeNode(String parentId, HttpServletRequest request) {

        List<Filter> filters = null;
        if(org.apache.commons.lang.StringUtils.isEmpty(parentId))
        {
            filters = RequestUtils.buildFilters(request);
            filters.add(new Filter("parentId", Operator.NL,null));
            filters.add(new Filter("visibled", YesNo.YES.getValue())); //过滤不可见的一级菜单
        }
        else
        {
            filters = new Filter.Builder().eq("parentId", parentId).build();
        }
        List<Order> orders = new ArrayList<Order>();
        orders.add(new Order("displayOrder", OrderType.ASC));

        List<Menu> list = menuService.select(filters, orders );

        String[] columns = {"menuCode", "moduleCode","menuName", "url", "displayOrder", "publicMenu", "menuTarget", "enabled", "visibled", "tips", "menuLevel", "leafNode","menuImage"};
        List<TreeNode> nodes = TreeUtils.parse(list, columns);

        return nodes;
    }

    /**
     * 保存
     * @param menu
     * @return
     */
    @ApiOperation(value = "保存一条数据")
    @PostMapping(value = "/save")
    public Map<String, Object> save(@RequestBody Menu menu) {

        Map<String, Object> tips = new HashMap<String, Object>();
        Boolean isExist = menuService.exists(menu.getMenuCode());
        try
        {
            if(isExist)
            {
                menuService.update(menu);
            }
            else
            {
                if(StringUtils.isNotBlank(menu.getParentId()))
                {
                    menu.setMenuCode(menu.getParentId() + "." + menu.getModuleCode());
                    menu.setUrl(menu.getParentId().replace(".", "/") + "/" + menu.getModuleCode());
                }
                else
                {
                    menu.setMenuCode(menu.getModuleCode());
                    menu.setUrl(menu.getModuleCode());
                }
                menuService.insert(menu);
            }
            tips.put(WebCode.SUCCESS, true);
            tips.put(WebCode.MSG, WebCode.SUCCESS_SAVE);
        }
        catch (ServiceException e)
        {
            tips.put(WebCode.SUCCESS, false);
            tips.put(WebCode.MSG, WebCode.FAILURE_SAVE);
        }
        return tips;
    }

    @ApiOperation(value = "移除节点")
    @PostMapping(value = "/removeNode/{id:.+}")
    public Map<String, Object> removeNode(@PathVariable String id) {
        Map<String, Object> tips = new HashMap<String, Object>();
        long count = menuService.count(new Filter.Builder().eq("parentId", id).build());
        if(count > 0)
        {
            tips.put(WebCode.SUCCESS, false);
            tips.put(WebCode.MSG, WebCode.DELETE_SUBNODE_FIRST);
        }
        else
        {
            //this.menuService.deleteByPrimaryKey(id);
            if(!id.equals("-1"))
                menuService.removeMenu(id);
            tips.put(WebCode.SUCCESS, true);
            tips.put(WebCode.MSG, WebCode.SUCCESS_DELETE);
        }
        return tips;
    }

    @ApiOperation(value = "验证提交的编码是否已经存在数据库中")
    @GetMapping(value = "/check", produces = "application/json;charset=UTF-8")
    public Map<String, Object> check(String code) {
        Map<String, Object> tips = new HashMap<String, Object>();

        Boolean exist = menuService.exists(code);
        tips.put("valid", !exist);

        return tips;
    }

}
